package com.zzjson.event;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : 自定义事件监听器</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年11月08日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class SpringEventListenerDemo {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext();

		//1.注册监听器
		context.addApplicationListener(new ApplicationListener<MyApplicationEvent>() {
			/**
			 * 3.监听器得到事件
			 * @param event
			 */
			@Override
			public void onApplicationEvent(MyApplicationEvent event) {
				Object source = event.getSource();
				System.out.println("接收到事件" + source);
				System.out.println("上下文" + event.getApplicationContext());
			}
		});
		context.refresh();
		//2.发布事件
		context.publishEvent(new MyApplicationEvent(context, "hello world"));
		context.publishEvent(new MyApplicationEvent(context, 1));
		context.publishEvent(new MyApplicationEvent(context, "事件3"));

	}

	private static class MyApplicationEvent extends ApplicationEvent {
		private ApplicationContext applicationContext;

		/**
		 * Create a new ApplicationEvent.
		 *
		 * @param source the object on which the event initially occurred (never {@code null})
		 */
		public MyApplicationEvent(ApplicationContext applicationContext, Object source) {
			super(source);
			this.applicationContext = applicationContext;
		}

		public ApplicationContext getApplicationContext() {
			return applicationContext;
		}
	}

}